package wnhz.com.business.groupshop.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.base.MyBaseActivity;
import wnhz.com.business.groupshop.bean.AddressBean;
import wnhz.com.business.groupshop.bean.AddressInfo;
import wnhz.com.business.constants.Constants;
import wnhz.com.business.groupshop.bean.ConfimOrderBean;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.uitls.BroadCastReceiverUtil;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.Prefer;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

/**
 * Created by wanghongchuang
 * on 2016/10/7.
 * email:844285775@qq.com
 */
public class ConfirmOrderActivity extends MyBaseActivity implements ActionBarClickListener, View.OnClickListener, BroadCastReceiverUtil.OnReceiveBroadcast {
    private static final String TAG = "ConfirmOrderActivity";

    @BindView(R.id.lay_address)
    LinearLayout layAddress;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.iv_left)
    LinearLayout left;
    @BindView(R.id.et_number)
    EditText number;
    @BindView(R.id.iv_right)
    LinearLayout right;
    @BindView(R.id.lay_mail)
    LinearLayout layMail;
    @BindView(R.id.tv_mail)
    TextView tvMail;
    @BindView(R.id.et_message)
    EditText Message;
    @BindView(R.id.tv_allprice)
    TextView allprice;
    @BindView(R.id.lay_submit)
    TextView lay_submit;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;
    @BindView(R.id.ll_address)
    LinearLayout ll_address;
    @BindView(R.id.ll_address_null)
    LinearLayout ll_address_null;
    @BindView(R.id.ry_confirmorder)
    RecyclerView ry_confirmorder;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_phone)
    TextView tv_phone;

    private List<ConfimOrderBean.GoodsBean> goodsBeanList = new ArrayList<>();
    private BaseRVAdapter adapter;
    private String token;
    private BroadcastReceiver broadcastReceiver;
    private int num = 1;
    private String goodsId;
    private String logo_pic;
    private String price;
    private String title;
    private String expree_fee;
    private String addressId = "";
    private String fromNumber;
    private String sku_Id = "";
    private String type = "";
    private String store_id = "";
    private String group_id = "";
    private String weight;
    private String goodsNum;

    private String address_status;
    private ConfimOrderBean orderBean;
    private static final int REQUEST_ADDRESS1 = 111;

    public static Intent createIntent(Context context, String goodsId, String sku_Id, String goodsNum,String type,String store_id) {
        Intent intent = new Intent(context, ConfirmOrderActivity.class);
        intent.putExtra("goodsId", goodsId);
        intent.putExtra("sku_Id", sku_Id);
        intent.putExtra("goodsNum", goodsNum);
        intent.putExtra("type", type);
        intent.putExtra("store_id", store_id);
        return intent;
    }

    private void parseIntent() {
        Intent intent = getIntent();
        goodsId = intent.getStringExtra("goodsId");
        sku_Id = intent.getStringExtra("sku_Id");
        goodsNum = intent.getStringExtra("goodsNum");
        type = intent.getStringExtra("type");
        store_id = intent.getStringExtra("store_id");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy);
        ButterKnife.bind(this);
        parseIntent();
        Log.e("商品id",goodsId);
        Log.e("skuid",sku_Id);
        Log.e("商品数量",goodsNum);
        SharedPreferences sp = getBaseContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        token = sp.getString("token", "");
        actionbar.setData("订单信息确认", R.drawable.ic_lefft_white, null, 0, null, 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        broadcastReceiver = BroadCastReceiverUtil.registerBroadcastReceiver(ConfirmOrderActivity.this, new String[]{Constants.ACTION_UPTATE_MONEY}, this);
        initView();
        LoadData();
    }

    private void LoadData() {
        Map<String,String> map = new HashMap<>();
        if(MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token",MyApplication.getInstance().getInfoBean().getToken());
        map.put("type",type); //1-自己开团  2-参团  3-单独购买
        map.put("status","1"); //1-拼团商城  2-返利商城
        map.put("goodsId",goodsId);
        map.put("store_id",store_id);
        map.put("sku_id",sku_Id);
        if (type.equals("2")){
            map.put("group_id",group_id);
        }
        map.put("num",goodsNum);
        map.put("is_free","0");// 是否免单  0-否  1-是
        map.put("password","");// 使用免单的验证  "UNOZH135790HACHA" 转 base64
        Log.e("goodsNum",goodsNum);
        Set<String> set = map.keySet();
        for (String s : set) {
            LogUtils.e("==获取订单===", s + ":" + map.get(s));
        }
        OkGo.<String>post(Url.ORDER_INDEX)
                .tag(this)
                .params(map,false)
                .execute(new DialogCallback<String>(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("确认订单页数据",response.body());
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String re = jsonObject.optString("re");
                        if (re.equals("1")) {
                            Gson gson = new Gson();
                            orderBean = gson.fromJson(response.body(),ConfimOrderBean.class);
                            handler.sendEmptyMessage(100);
                        }else {
                            MyToast("获取订单信息失败");
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.e("商品下单",response.getException().toString());
                    }
                });
    }

    @Override
    protected void handleMsg(android.os.Message msg) {
        switch (msg.what){
            case 100:
                if (orderBean.getAddress_status().equals("1")){
                    tv_name.setText(orderBean.getAddress().getConsignee());
                    String tel = orderBean.getAddress().getTelephone();
                    tv_phone.setText(tel.substring(0,3)+"****"+tel.substring(7,tel.length()));
                    tvAddress.setText(orderBean.getAddress().getProvince()+orderBean.getAddress().getCity()+orderBean.getAddress().getDistrict()+orderBean.getAddress().getPlace());
                }
                if (orderBean.getGoods().size() > 0){
                    goodsBeanList = orderBean.getGoods();
                    initGoodsList(goodsBeanList);
                }
                number.setText(orderBean.getNum());
                if (orderBean.getExpress_fee().equals("0")){
                    tvMail.setText("包邮");
                }else {
                    tvMail.setText("¥"+orderBean.getExpress_fee());
                }
                allprice.setText("¥"+orderBean.getTotal());
                break;
        }
    }

    /**
     * 填充商品列表
     */
    private void initGoodsList(final List<ConfimOrderBean.GoodsBean> goodsBean) {
        ry_confirmorder.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        adapter = new BaseRVAdapter(this,goodsBean) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_confirmorder;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                Glide.with(ConfirmOrderActivity.this).load(goodsBean.get(position).getLogo_pic()).into(holder.getImageView(R.id.iv_avatar));
                holder.setTextView(R.id.tv_collect,goodsBean.get(position).getGoods_name());
                holder.setTextView(R.id.tv_newPrice,"¥"+goodsBean.get(position).getPrice());
                TextView tv_oldPrice = holder.getTextView(R.id.tv_oldPrice);
                tv_oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                tv_oldPrice.setText("¥"+orderBean.getGoods().get(position).getOprice());
                holder.setTextView(R.id.tv_sales,goodsBean.get(position).getSku_info());
            }
        };
        ry_confirmorder.setAdapter(adapter);
    }

    private void initView() {
        layAddress.setOnClickListener(this);
        left.setOnClickListener(this);
        right.setOnClickListener(this);
        lay_submit.setOnClickListener(this);

        number.setText("0");

        number.postInvalidate();
        //切换后将EditText光标置于末尾
        CharSequence charSequence = number.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_address:
                Intent intent = new Intent(ConfirmOrderActivity.this, AddressActivity.class);
                intent.putExtra("from", "1");
                startActivityForResult(intent, REQUEST_ADDRESS1);

                break;
            case R.id.iv_left:
                if (number.getText().toString().equals("")) {
                    ToastUtils.showToast(ConfirmOrderActivity.this, "购物数量不可为空");
                    return;
                }

                num = Integer.parseInt(number.getText().toString());
                num = num - 1;
                if (num <= 1) {
                    ToastUtils.showToast(getBaseContext(), "就剩一件喽！");
                    number.setText(String.valueOf(1));
                } else {
                    number.setText(String.valueOf(num));
                }

                BroadCastReceiverUtil.sendBroadcast(getBaseContext(), Constants.ACTION_UPTATE_MONEY);
                break;
            case R.id.iv_right:
                if (number.getText().toString().equals("")) {
                    ToastUtils.showToast(ConfirmOrderActivity.this, "购物数量不可为空");
                    return;
                }

                num = Integer.parseInt(number.getText().toString());
                num = num + 1;
                number.setText(String.valueOf(num));

                BroadCastReceiverUtil.sendBroadcast(getBaseContext(), Constants.ACTION_UPTATE_MONEY);
                break;
            case R.id.lay_submit:
//                if (addressId.equals("")) {
//                    ToastUtils.showToast(ConfirmOrderActivity.this, "请选择收货地址");
//                    return;
//                }
//
//                if (number.getText().toString().equals("") || number.getText().toString().equals("0")) {
//                    ToastUtils.showToast(ConfirmOrderActivity.this, "购物数量不可为空或0");
//                    return;
//                }
//
//                pay_now();

                startActivity(PayActivity.createIntent(ConfirmOrderActivity.this, "" ,"", ""));
                break;
        }
    }

    //提交订单
    private void pay_now() {
        LogUtils.e("== 提交订单 选择的sku ==", sku_Id);
        showDialog("提交中...");
        Map<String, Object> map = new HashMap<>();
        map.clear();
        map.put("token", token);
        map.put("addressId", addressId);
        map.put("goodsId", goodsId);
        if (!sku_Id.equals("")) {
            map.put("sku_id", sku_Id);
        }
        map.put("nums", number.getText().toString());
        map.put("express_fee", expree_fee);
        map.put("comment", Message.getText().toString());

        XUtil.Post(Url.ORDER_MAKEORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("== 提交订单 按钮 ==", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("re").equals("0")) {
                        ToastUtils.showToast(ConfirmOrderActivity.this, jsonObject.optString("info"));
                    } else if (jsonObject.optString("re").equals("1")) {
                        Double all_price = Double.parseDouble(price) * Integer.valueOf(number.getText().toString());

//                        startActivity(PayActivity.createIntent(ConfirmOrderActivity.this, jsonObject.optString("order_id"), jsonObject.optString("order_no"), str, "1"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onEditTextClick() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BroadCastReceiverUtil.unRegisterBroadcastReceiver(ConfirmOrderActivity.this, broadcastReceiver);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        switch (action) {
            case Constants.ACTION_UPTATE_MONEY:
//                allprice.setText("¥ " + (Double.parseDouble(price) * Integer.valueOf(number.getText().toString()) + Double.parseDouble(expree_fee)));

//                if (!addressId.equals("")) {
//                    getYF(addressId);
//                }
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ADDRESS1)
            if (resultCode == RESULT_OK) {
                //处理扫描结果（在界面上显示）
                if (null != data) {
                    ll_address_null.setVisibility(View.GONE);
                    ll_address.setVisibility(View.VISIBLE);
                    AddressInfo.InfoBean infoBean = (AddressInfo.InfoBean) data.getSerializableExtra("addressBean");
                    addressId = infoBean.getAid();

                    tv_name.setText(infoBean.getConsignee());
                    tv_phone.setText(infoBean.getTelephone());
                    tvAddress.setText(infoBean.getProvince() + infoBean.getCity() + infoBean.getAddress() + infoBean.getPlace() + infoBean.getDoorplate());

//                    getYF(addressId);
                }

                super.onActivityResult(requestCode, resultCode, data);
            }
    }


    //获取邮费
    public void getYF(String addressId) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", Prefer.getInstance().getToken());
        map.put("addressId", addressId);
        map.put("type", "1");
        map.put("num", number.getText().toString());
        map.put("goodsId", goodsId);

        XUtil.Post(Url.MEMBER_CALCULATEPOSTAGE, map, new MyCallBack<String>() {

            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("=====总合计  邮费=======", result);

                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("re").equals("1")) {
                        if (jsonObject.optString("info").equals("0")) {
                            tvMail.setText("快递 包邮");
                        } else {
                            tvMail.setText("邮费 : ¥ " + jsonObject.optString("info"));
                        }

                        expree_fee = jsonObject.optString("info");
                        allprice.setText("¥ " + (Double.parseDouble(price) * Integer.valueOf(number.getText().toString()) + Double.parseDouble(expree_fee)));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

}
